package beans;


import database.DatabaseConnection;
import database.Sql;

import java.io.IOException;
import java.io.PrintWriter;

import java.math.BigDecimal;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import java.util.ArrayList;
import java.util.Iterator;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.faces.event.ValueChangeEvent;

import javax.servlet.http.HttpServletResponse;

import obj.StudentObject;

import oracle.adf.view.rich.component.rich.data.RichTable;
import oracle.adf.view.rich.component.rich.input.RichInputText;
import oracle.adf.view.rich.component.rich.layout.RichPanelFormLayout;
import oracle.adf.view.rich.component.rich.layout.RichPanelGroupLayout;
import oracle.adf.view.rich.context.AdfFacesContext;
import oracle.adf.view.rich.datatransfer.DataFlavor;
import oracle.adf.view.rich.datatransfer.Transferable;
import oracle.adf.view.rich.dnd.DnDAction;
import oracle.adf.view.rich.event.DropEvent;

import org.apache.myfaces.trinidad.context.RequestContext;
import org.apache.myfaces.trinidad.event.SelectionEvent;
import org.apache.myfaces.trinidad.model.RowKeySet;
import org.apache.myfaces.trinidad.model.UploadedFile;
import org.apache.myfaces.trinidad.render.ExtendedRenderKitService;
import org.apache.myfaces.trinidad.util.Service;

import view.FormularInterface;


/** * Drag and drop handler that handles the table row drop onto * an input form
 * @author emilia
 */


public class StudentFormularBB implements FormularInterface {
    private RichPanelFormLayout panelFormLayoutFormular;
    private RichPanelFormLayout panelFormLayoutFormularLogin;

    private static final long serialVersionUID = 1L;
    ArrayList<StudentObject> listaStudent = new ArrayList<StudentObject>();
    private RichTable tableStudenti;
    private String output;
    private boolean outputRendered = false;
    private BigDecimal id_student;
    private String name;
    private String password;
    private RichPanelGroupLayout panelGroupLayout;
    public int idStudent;

    public StudentFormularBB() {
        student();
    }
      
    @Override
    public void insert(ActionEvent actionEvent) {
        String nume = null;
        String prenume = null;
        String email = null;
        String master = null;
        int nr;
        for (UIComponent uiComp : panelFormLayoutFormular.getChildren()) {
            RichInputText input = (RichInputText)uiComp;
            if (uiComp.getId().equalsIgnoreCase("itNume")) {
                nume = (String)input.getValue();

            }
            if (uiComp.getId().equalsIgnoreCase("itPrenume")) {
                prenume = (String)input.getValue();
            }
            if (uiComp.getId().equalsIgnoreCase("itMaster")) {
                master = (String)input.getValue();
            }
            if (uiComp.getId().equalsIgnoreCase("itEmail")) {
                email = (String)input.getValue();
            }
        }
        insert(nume, prenume, email, master);
    }

    @Override
    public void update(ActionEvent actionEvent) {
        String nume = null;
        String prenume = null;
        String email = null;
        String master = null;
        int nr = -1;
        Connection con = null;
        Statement stmt1 = null;
        Statement stmt2 = null;
        Statement stmt3 = null;
        PrintWriter pw = null;
        ResultSet rs = null;

        try {
            con = DatabaseConnection.getConectare();
            stmt1 = con.createStatement();


            for (UIComponent uiComp : panelFormLayoutFormular.getChildren()) {
                RichInputText input = (RichInputText)uiComp;
                if (uiComp.getId().equalsIgnoreCase("itNr")) {
                    if (input.getValue() != null) {
                        nr = (Integer)input.getValue();
                    }

                }
                if (uiComp.getId().equalsIgnoreCase("itNume")) {
                    nume = (String)input.getValue();

                }
                if (uiComp.getId().equalsIgnoreCase("itPrenume")) {
                    prenume = (String)input.getValue();
                }
                if (uiComp.getId().equalsIgnoreCase("itMaster")) {
                    master = (String)input.getValue();
                }
                if (uiComp.getId().equalsIgnoreCase("itEmail")) {
                    email = (String)input.getValue();
                }
            }
            String sqlSelect = " select * from student where id_student=" + nr;
            String sqlUpdate =
                " update student set  nume='" + nume + "', prenume='" + prenume + "',email='" + email + "',master='" +
                master + "'" + " where id_student=" + nr;

            rs = stmt1.executeQuery(sqlSelect);

            if (rs.next()) {
                stmt2 = con.createStatement();
                stmt2.executeUpdate(sqlUpdate);
                System.out.println("Update" + sqlUpdate);
            } else {

            }

        } catch (ClassNotFoundException ex) {

        } catch (SQLException ex) {
            System.out.println("eroare sql " + ex);
        } finally {

            try {
                if (stmt1 != null)
                    stmt1.close();
                if (stmt2 != null)
                    stmt2.close();
                if (rs != null)
                    rs.close();
            } catch (SQLException ex) {
            }
        }
    }

    public void insert(String nume, String prenume, String email, String master) {
        if (nume != null && prenume != null && master != null) {
            Connection con = null;
            Statement stmt1 = null;
            try {
                con = DatabaseConnection.getConectare();
                stmt1 = con.createStatement();
                int nr = Sql.generateID("STUDENT", "ID_STUDENT");
                String sqlInsert =
                    " insert into student (id_student,username,nume,prenume,email,master,parola) values (" + nr +
                    ",'" + nume + prenume + "'," + "'" + nume + "','" + prenume + "','" + email + "','" + master +
                    "','a')";
                int executeUpdate = stmt1.executeUpdate(sqlInsert);
            } catch (ClassNotFoundException ex) {

            } catch (SQLException ex) {
                System.out.println("eroare sql " + ex);
            } finally {

                try {
                    if (stmt1 != null)
                        stmt1.close();

                } catch (SQLException ex) {
                }
            }
        }
    }


    public void login(ActionEvent actionEvent) {
        String url = null;
        Connection con = null;
        Statement stmt = null;
        ResultSet rs = null;
        PrintWriter pw = null;
        try {
            con = DatabaseConnection.getConectare();
            stmt = con.createStatement();
            System.out.println("Nume" + getName() + getPassword());
            rs =
 stmt.executeQuery(" select id_student from student where username= '" + getName() + "' and parola= '" +
                   getPassword() + "'");

            if (rs.next()) {
                id_student = rs.getBigDecimal("id_student");
                idStudent = id_student.intValue();
                System.out.println("###" + idStudent);
            }
        } catch (ClassNotFoundException ex) {
        } catch (SQLException ex) {
            System.out.println("eroare sql " + ex);
        } finally {
            try {
                if (rs != null)
                    rs.close();
            } catch (SQLException ex) {

            }
            try {
                if (stmt != null)
                    stmt.close();
            } catch (SQLException ex) {

            }
        }
        if (id_student != null) { //  redirect to a other url
            ExternalContext ectx;
            ectx = FacesContext.getCurrentInstance().getExternalContext();
            HttpServletResponse response;
            response = (HttpServletResponse)ectx.getResponse();
            url = "http://127.0.0.1:7101" + ectx.getRequestContextPath() + "/faces/student.jsf";
            try {
                response.sendRedirect(url);
            } catch (Exception ex) {
                ex.printStackTrace();
                System.out.println("Eroareee" + ex);
            }
        } else {
            System.out.println("Username or password is wrong");
            output = "Username or password is wrong !";
            outputRendered = true;
            RequestContext context = RequestContext.getCurrentInstance();
            context.addPartialTarget(panelGroupLayout);
        }

    }


    public void loadList(ValueChangeEvent valueChangeEvent) {
        System.out.println("########incarcaLista");
        //Stergem tabelul
        if (listaStudent != null && !listaStudent.isEmpty()) {
            listaStudent.clear();
        }
        UploadedFile file = (UploadedFile)valueChangeEvent.getNewValue();
        if (file != null) {
            FacesContext context = FacesContext.getCurrentInstance();
            FacesMessage message =
                new FacesMessage("Successfully uploaded file " + file.getFilename() + " (" + file.getLength() +
                                 " bytes)");
            context.addMessage(valueChangeEvent.getComponent().getClientId(context), message);
        }

        try {
            parseISToString(file.getInputStream());
        } catch (IOException e) {

        }
        AdfFacesContext context = AdfFacesContext.getCurrentInstance();
        context.addPartialTarget(tableStudenti);
    }

    public String parseISToString(java.io.InputStream is) {
        java.io.DataInputStream dis = new java.io.DataInputStream(is);
        Connection con = null;
        Statement stmt = null;
        try {
            con = DatabaseConnection.getConectare();
            stmt = con.createStatement();
            String sql = "delete  from materie_student";
            stmt.executeUpdate(sql);
        } catch (ClassNotFoundException ex) {
        } catch (SQLException ex) {
        } finally {
            try {
                if (stmt != null)
                    stmt.close();
            } catch (SQLException ex) {

            }
        }
        try {
            String line = null;
            while (dis.available() != 0) {
                String phrase = dis.readLine();
                String delims = "[ ]+";
                String[] tokens = phrase.split(delims);
                String nume = tokens[0];
                String prenume = tokens[1];
                String email = tokens[2];
                StudentObject s = new StudentObject();
                s.setNume(nume);
                s.setPrenume(prenume);
                s.setEmail(email);
                listaStudent.add(s);
                insert(s.getNume(), s.getPrenume(), s.getEmail(), s.getMaster());
            }
        } catch (Exception ex) {
            ex.getMessage();
        } finally {
            try {
                is.close();
            } catch (Exception ex) {
            }
        }
        return "";
    }

    public void student() {
        listaStudent.clear();
        Connection con = null;
        Statement stmt = null;
        ResultSet rs = null;
        PrintWriter pw = null;
        try {
            con = DatabaseConnection.getConectare();
            stmt = con.createStatement();
            rs =
 stmt.executeQuery(" select id_student,nume, initiala_tatalui, prenume, credite,email,poza, parola,master from student ");
            while (rs.next()) {
                BigDecimal id_student = rs.getBigDecimal("id_student");
                System.out.println("AM inrreg " + id_student);
                String nume = rs.getString("nume");
                String initiala_tatalui = rs.getString("initiala_tatalui");
                String prenume = rs.getString("prenume");
                String parola = rs.getString("parola");
                BigDecimal credite = rs.getBigDecimal("credite");
                String email = rs.getString("email");
                String poza = rs.getString("poza");
                String master = rs.getString("master");
                StudentObject s = new StudentObject();
                s.setId_student(id_student);
                s.setNume(nume);
                s.setInitiala_tatalui(initiala_tatalui);
                s.setPrenume(prenume);
                s.setEmail(email);
                s.setParola(parola);
                s.setPoza(poza);
                s.setMaster(master);
                s.setCredite(credite);
                listaStudent.add(s);
            }
        } catch (ClassNotFoundException ex) {
        } catch (SQLException ex) {
        } finally {
            try {
                if (rs != null)
                    rs.close();
            } catch (SQLException ex) {

            }
            try {
                if (stmt != null)
                    stmt.close();
            } catch (SQLException ex) {

            }
        }
    }
    public void selectionTable(SelectionEvent selectionEvent) {
        RichTable _mainTable = (RichTable)selectionEvent.getSource();
        Object _selectedrowdata = _mainTable.getSelectedRowData();
        StudentObject s = (StudentObject)_selectedrowdata;
        name = s.getNume() + "" + s.getPrenume();
        setId_student(s.getId_student());
        System.out.println("Am descoperit" + id_student);
        RequestContext context = RequestContext.getCurrentInstance();
        context.addPartialTarget(panelFormLayoutFormularLogin);
    }

    @Override
    public void refreshTable(ActionEvent actionEvent) {
        student();
        AdfFacesContext context = AdfFacesContext.getCurrentInstance();
        context.addPartialTarget(tableStudenti);
    }
    //method referenced from the af:dropTarget

    public DnDAction dropHandler(DropEvent dropEvent) {
        //access the drag source, the table to read the rowKey
        ////representing the row
        RichTable table = (RichTable)dropEvent.getDragComponent();
        Transferable t = dropEvent.getTransferable();
        DataFlavor<RowKeySet> df = DataFlavor.getDataFlavor(RowKeySet.class, "rowcopy");
        RowKeySet rks = t.getData(df);
        Iterator iter = rks.iterator();
        //sample is set up for single row drag and drop
        if (iter.hasNext()) {
            //get next selected row key
            Integer key = (Integer)iter.next();
            table.setRowKey(key);
            //get handle to drop component
            RichPanelFormLayout panelFormLayout = (RichPanelFormLayout)dropEvent.getDropComponent();
            //JUCtrlHierNodeBinding is the object in ADF that represents //a row in a table or a node in a tree. The object wraps the
            //actual table row object, which in the case of ADF BC is

            Object rowBinding = (Object)table.getRowData();
            StudentObject studentDropRow = (StudentObject)rowBinding;
            //the row that is actually dragged from the ADF Faces table

            //update current row in form if the table row is not null
            if (studentDropRow != null) {
                //to evaluate and update the manager Id field, we need to create
                //and store a handle to it. The bean is in request (or backing
                //bean scop, so no overhead)

                //search all panelFormLayout component children for the
                //update more than 2 fields

                for (UIComponent uiComp : panelFormLayout.getChildren()) {

                    if (uiComp.getId().equalsIgnoreCase("itNr")) {
                        ((RichInputText)uiComp).resetValue();
                        ((RichInputText)uiComp).setValue(studentDropRow.getId_student());
                    }

                    if (uiComp.getId().equalsIgnoreCase("itNume")) {
                        System.out.println("Randul selectat este=" + uiComp.getClientId());
                        ((RichInputText)uiComp).resetValue();
                        ((RichInputText)uiComp).setValue(studentDropRow.getNume());

                    }
                    if (uiComp.getId().equalsIgnoreCase("itPrenume")) {
                        ((RichInputText)uiComp).resetValue();
                        ((RichInputText)uiComp).setValue(studentDropRow.getPrenume());
                    }
                    if (uiComp.getId().equalsIgnoreCase("itMaster")) {
                        ((RichInputText)uiComp).resetValue();
                        ((RichInputText)uiComp).setValue(studentDropRow.getMaster());
                    }
                    if (uiComp.getId().equalsIgnoreCase("itEmail")) {
                        ((RichInputText)uiComp).resetValue();
                        ((RichInputText)uiComp).setValue(studentDropRow.getEmail());
                    }
                }

            }
            FacesContext fctx = FacesContext.getCurrentInstance();
            ExtendedRenderKitService erks = Service.getRenderKitService(fctx, ExtendedRenderKitService.class);
            erks.addScript(fctx, "AdfPage.PAGE.clearAllMessages();");
            return DnDAction.COPY;
        }
        //no drag and drop happened
        {
            return DnDAction.NONE;
        }
    }

    public ArrayList<StudentObject> getListaStudent() {
        return listaStudent;
    }

    public String getOutput() {
        return output;
    }

    public boolean isOutputRendered() {
        return outputRendered;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getPassword() {
        return password;
    }

    public void setTableStudenti(RichTable tableStudenti) {
        this.tableStudenti = tableStudenti;
    }

    public RichTable getTableStudenti() {
        return tableStudenti;
    }


    public void setPanelGroupLayout(RichPanelGroupLayout panelGroupLayout) {
        this.panelGroupLayout = panelGroupLayout;
    }

    public RichPanelGroupLayout getPanelGroupLayout() {
        return panelGroupLayout;
    }

    public void setListaStudent(ArrayList<StudentObject> listaStudent) {
        this.listaStudent = listaStudent;
    }

    public void setId_student(BigDecimal id_student) {
        this.id_student = id_student;
    }

    public BigDecimal getId_student() {
        return id_student;
    }

    public void setPanelFormLayoutFormularLogin(RichPanelFormLayout panelFormLayoutFormularLogin) {
        this.panelFormLayoutFormularLogin = panelFormLayoutFormularLogin;
    }

    public RichPanelFormLayout getPanelFormLayoutFormularLogin() {
        return panelFormLayoutFormularLogin;
    }

    public void setIdStudent(int idStudent) {
        this.idStudent = idStudent;
    }

    public int getIdStudent() {
        return idStudent;
    }
    public void setPanelFormLayoutFormular(RichPanelFormLayout panelFormLayoutFormular) {
        this.panelFormLayoutFormular = panelFormLayoutFormular;
    }

    public RichPanelFormLayout getPanelFormLayoutFormular() {
        return panelFormLayoutFormular;
    }


}
